<!-- effectScope 多次 run + onScopeDispose 演示 -->
<script setup>
import { reactive, effectScope, effect, onScopeDispose, ref } from "vue";

const dummy = ref(0); // 存储 counter.num
const doubled = ref(0); // 存储 counter.num * 2
const cleanupCount = ref(0); // 统计 onScopeDispose 调用次数
const counter = reactive({ num: 0 });
const stopped = ref(false);

// 创建作用域
const scope = effectScope();

// 第一次 run
scope.run(() => {
  effect(() => {
    dummy.value = counter.num;
    console.log("%c[effect1] dummy =", "color: #e67e22", dummy.value);
  });

  onScopeDispose(() => {
    cleanupCount.value += 1;
    console.log("%c[cleanup1] 执行 +1", "color: #9b59b6");
  });
  onScopeDispose(() => {
    cleanupCount.value += 2;
    console.log("%c[cleanup2] 执行 +2", "color: #8e44ad");
  });
});

// 第二次 run
scope.run(() => {
  effect(() => {
    doubled.value = counter.num * 2;
    console.log("%c[effect2] doubled =", "color: #1abc9c", doubled.value);
  });

  onScopeDispose(() => {
    cleanupCount.value += 4;
    console.log("%c[cleanup3] 执行 +4", "color: #16a085");
  });
});

// 点击增加
const increase = () => {
  counter.num++;
};

// 停止作用域
const stopScope = () => {
  console.log(
    "%c停止作用域 -> 触发所有 onScopeDispose",
    "color: red; font-weight: bold;"
  );
  scope.stop();
  stopped.value = true;
};
</script>

<template>
  <div style="padding: 20px">
    <h3>effectScope: 多次 run + onScopeDispose 演示</h3>

    <p>counter.num: {{ counter.num }}</p>
    <p>dummy: {{ dummy }}</p>
    <p>doubled: {{ doubled }}</p>
    <p>cleanupCount（onScopeDispose 执行总和）: {{ cleanupCount }}</p>

    <button :disabled="stopped" @click="increase">增加 counter</button>
    <button :disabled="stopped" @click="stopScope">停止作用域</button>

    <p style="color: #666; font-size: 14px; margin-top: 10px">
      打开控制台查看：不同颜色日志表示不同的 effect 与 onScopeDispose
      执行顺序。<br />
      点击“停止作用域”后，会依次触发所有清理回调，总和应为 7。
    </p>
  </div>
</template>

<style scoped>
button {
  margin-right: 8px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #ccc;
  cursor: pointer;
}
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
